package com.wyx.controller;

import com.wyx.pojo.Category;
import com.wyx.pojo.Result;
import com.wyx.service.CategoryService;
import com.wyx.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Validated
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @PostMapping("/add")
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        if(!categoryService.selectCategoryByAll(category).isEmpty())
            return Result.error("分类已存在");
        Map<String,Object> map= ThreadLocalUtil.get();
        category.setCreateUser((int)map.get("id"));
        categoryService.insertCategory(category);
        return Result.success();
    }
    @GetMapping("/list")
    public Result list() {
        Map<String,Object> map= ThreadLocalUtil.get();
        Category category = new Category();
        category.setCreateUser((int)map.get("id"));
        return Result.success(categoryService.selectCategoryByAll(category));
    }
    @GetMapping("/detail")
    public Result detail(int id) {
        Category category = new Category();
        category.setId(id);
        return Result.success(categoryService.selectCategoryByAll(category).get(0));
    }
    @PutMapping("/update")
    public Result update(@RequestBody @Validated(Category.Update.class) Category category) {
        System.out.println(category);
        categoryService.updateCategoryById(category);
        return Result.success();
    }
    @GetMapping("/delete")
    public Result delete(int id) {
        categoryService.deleteCategoryById(id);
        return Result.success();
    }
}
